<template>
  <div id="menuConfigCustomeruration">
    <el-card class="box-card">
      <!-- 头部 -->
      <template #header>
        <div class="card-header">
          <span>文件上传配置</span>
        </div>
      </template>
      <div style="display: flex; justify-content: space-between">
        <el-button type="primary" @click="addhandleClick">新增</el-button>
        <el-input
          style="width: 230px"
          clearable
          :prefix-icon="Search"
          v-model="tableConfig.search"
          placeholder="请输入..."
          @change="handleSearch"
        >
          <template #append>
            <span class="search" @click="handleSearch">搜索</span>
          </template>
        </el-input>
      </div>
      <el-tabs
        v-model="activeName"
        class="demo-tabs"
        @tab-click="handleClickTab"
      >
        <el-tab-pane label="营销图库" name="first"> </el-tab-pane>
        <el-tab-pane label="资源下载" name="second"> </el-tab-pane>
      </el-tabs>
      <tableList :columns="columns" :tableData="tableData">
        <template #cover_img="{ row }">
          <ProcessedImage
            :src="row.cover_img"
            v-if="row.cover_img"
            params="imageView2/1/w/100/h/57"
          />
          <!-- <img class="img" :src="row.cover_img" /> -->
        </template>
        <template #operation="{ row }">
          <Edit
            @click="saveEdit(row)"
            style="width: 1.5em; height: 1.5em; cursor: pointer"
          />
          <delete
            @click="del(row)"
            style="
              width: 1.5em;
              height: 1.5em;
              cursor: pointer;
              margin-left: 10px;
            "
          />
        </template>
      </tableList>
      <div class="pagintion" style="margin-top: 20px">
        <pagintion
          :tableConfig="tableConfig"
          @sizeChange="sizeChange"
          @currentChange="currentChange"
        ></pagintion>
      </div>
    </el-card>
    <Dialog
      :title="title"
      :append-to-body="true"
      v-model:dialogFormVisible="visiteDialog"
      @handleClick="handleClick"
      @handleClose="handleClose"
    >
      <template #center>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="params"
          :rules="rules"
          class="demo-ruleForm"
          status-icon
          label-position="right"
        >
          <el-form-item label="二级标题" prop="title_Two" label-width="80">
            <el-select
              v-model="params.title_Two"
              multiple
              placeholder="请选择二级分类标题"
              style="width: 500px"
              @change="selectChangeTwo"
            >
              <el-option
                v-for="item in titleTwoList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="资源名称" prop="name" label-width="80">
            <el-input v-model="params.name" />
          </el-form-item>
          <el-form-item label="文件上传" prop="file" label-width="80">
            <uploadFiled
              @fileList="fileList"
              :fileType="params"
              ref="uploadFile"
            ></uploadFiled>
          </el-form-item>
          <el-form-item label="封面图" prop="cover" label-width="80">
            <ImageUpload
              :limit="1"
              :height="400"
              :modelValue="modelValueList"
              @update:modelValue="modelValue"
            />
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import pagintion from '@/components/Pagintions/pagintion.vue';
import { Search } from '@element-plus/icons-vue';
import tableList from './module/tableList.vue';
import Dialog from './module/dialog.vue';
import marketing from '@/modules';
import { ElMessage } from 'element-plus';
import { onMounted } from 'vue';
import uploadFiled from '@/components/qiniuFileUpload';
const {
  marketingListApi,
  resourcesListApi,
  zYApi,
  titleApi,
  editApi,
  zYdelApi,
} = marketing; //addMarketingApi
const activeName = ref('first');
const visiteDialog = ref(false);
const ruleFormRef = ref(null);
const modelValueList = ref(null);
const uploadFile = ref(null);
const title = ref('新增');
// const fileModelValueList = ref([]);
const titleOne = ref([]);
const titleTwo = ref([]);
const titleTwoList = ref([]);
const current = ref(0);
const dataList = ref([]);
const columns = ref([
  { label: '封面', prop: 'cover_img', width: '218' },
  { label: '资源名称', prop: 'name', width: '296', type: 'name' },
  //   { label: '所属分类', prop: 'className', width: '270' },
  {
    label: '文件格式',
    prop: 'fileType',
    width: '270',
  },
  { label: '文件大小', prop: 'fileSize', width: '150' },
  { label: '热度', prop: 'sort', width: '150' },
  { label: '上架时间', prop: 'create_time', width: '200' },
  {
    label: '操作',
    prop: 'operation',
  },
]);
const tableConfig = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  search: '',
  type: 1,
});
const params = ref({
  typeClass: 1,
  id: '',
  name: '',
  url: '',
  cover: '',
  className: '',
  fileSize: '',
  twoTitle: '',
  // title_One: [],
  title_Two: [],
  fileType: '',
});
// 搜索
const handleSearch = () => {
  tableConfig.value.page = 1;
  current.value == 0 ? resourcestableData() : zYtableData();
};
const tableData = ref([]);
const modelValue = (val) => {
  modelValueList.value = val;
  params.value.cover = val;
};
const handleClickTab = (tab) => {
  current.value = tab.index;
  params.value.title_Two == [];
  tab.index == 0 ? (tableConfig.value.type = 1) : (tableConfig.value.type = 2);
  tab.index == 0 ? (params.value.typeClass = 1) : (params.value.typeClass = 2);
  params.value.typeClass == 1
    ? (titleTwoList.value = titleTwo.value)
    : (titleTwoList.value = titleOne.value);

  tab.index == 0 ? resourcestableData() : zYtableData();

  marketingList();
};
const selectChangeTwo = (val) => {
  const selectedItems = titleTwoList.value.filter((item) =>
    val.includes(item.id)
  );
  const keyValuePairs = selectedItems.map((item) => ({
    id: item.id,
    name: item.name,
  }));
  params.value.twoTitle = JSON.stringify(keyValuePairs);
  // 提取 name 字段并用逗号隔开
  const names = keyValuePairs.map((item) => item.name).join(', ');
  params.value.className = names;
};
//一级标题和二级标题
const titleList = async () => {
  const { data } = await titleApi({ type: tableConfig.value.type });
  titleOne.value = data.aclass;
  titleTwo.value = data.bclass;
  titleTwoList.value = data.bclass;
};
// 上传文件的src
const fileList = ({ response, file }) => {
  if (response) {
    response ? (params.value.url = '/' + response.key) : '';
    file ? (params.value.fileSize = (file.size / 1024).toFixed(2)) : '';
    let extension = file.name.split('.').pop(); // 使用 split 分割并取最后一个部分
    extension ? (params.value.file = extension) : '';
  }
};
// 新增
const addhandleClick = () => {
  visiteDialog.value = true;
  uploadFile.value?.clearList();
  title.value = '新增';
  delete tableConfig.value.total;
  modelValueList.value = [];
  Object.assign(params.value, {
    id: 0,
    name: '',
    url: '',
    cover: '',
    fileSize: '',
    title_Two: [], // 重置为空数组
    fileType: '',
  });
};
const editClick = async (params) => {
  // 删除不需要的字段
  delete tableConfig.value.total;
  const res = await editApi(params);
  if (res.code == 20000) {
    ElMessage({
      message: res.msg,
      type: 'success',
    });
    current.value == 0 ? resourcestableData() : zYtableData();
  }
};
const saveEdit = (row) => {
  const ids = row.title_Two.map((item) => item.resource_id);
  const data = titleTwoList.value.filter((item) => ids.includes(item.id));
  visiteDialog.value = true;
  title.value = '编辑';
  modelValueList.value = row.cover_img;
  params.value.cover = row.cover_img;
  params.value.fileType = row.fileType;
  params.value.twoTitle = JSON.stringify(data);
  // 将 title_Two 转换为 JSON 字符串
  const { title_Two, sort, name, id, fileSize } = row;
  console.log('fileSize:', fileSize);
  params.value.title_Two = title_Two.map((item) => item.resource_id);

  Object.assign(params.value, {
    sort,
    name,
    id,
    fileSize,
  });
};
const handleClick = async () => {
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      title.value == '编辑'
        ? JSON.stringify(params.value.title_Two)
        : params.value.title_Two;
      editClick(params.value);
      visiteDialog.value = false;
    }
  });
};
const handleClose = (val) => {
  visiteDialog.value = val;
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate();
  }
};
const rules = reactive({
  cover: [{ required: true, message: '请输入封面图', trigger: 'blur' }],
  name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
  title_Two: [
    { required: true, message: '请选择二级分类标题', trigger: 'blur' },
  ],
});
// 分页
const sizeChange = (val) => {
  tableConfig.pageSize = val;
  current.value == 0 ? resourcestableData() : zYtableData();
};
const currentChange = (val) => {
  tableConfig.page = val;
  current.value == 0 ? resourcestableData() : zYtableData();
};
const delApi = async (id) => {
  const type = tableConfig.value.type;
  const data = await zYdelApi({ id, type });
  if (data.code == 20000) {
    ElMessage({
      message: data.msg,
      type: 'success',
    });
    current.value == 0 ? resourcestableData() : zYtableData();
  }
};
//删除
const del = (row) => {
  delApi(row.id);
};
// 营销图库
const marketingList = async () => {
  const { data } = await marketingListApi({
    type: tableConfig.value.type,
  });
  dataList.value = data;
};
// 资源下载列表
const zYtableData = async () => {
  const { page, pageSize, type, search } = tableConfig.value;
  const { data } = await zYApi({ page, pageSize, type, search });
  tableData.value = data.data;
  tableConfig.value.total = data.total;
};
// 营销图库列表
const resourcestableData = async () => {
  const { page, pageSize, type, search } = tableConfig.value;
  const { data } = await resourcesListApi({ page, pageSize, type, search });
  tableData.value = data.data;
  tableConfig.value.total = data.total;
};
onMounted(() => {
  marketingList();
  resourcestableData();
  titleList(); //获取一级二级标题
});
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.row-bg {
  .el-form-item {
    margin: 10px 0 20px;
  }
}

.alitem {
  .icon-button {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 10px;
    /* 将光标设置为手型 */
    cursor: pointer;
  }
}
.img {
  width: 80px;
  height: 80px;
}
</style>
